var express = require('express');
var router = express.Router();
var uuid = require('uuid').v1;


router.get('/url', async function (req, res, next) {
    var projectId = req.query.projectId;
    var Sql = `SELECT * FROM project_url WHERE project_id = ? AND disable = 0`;
    try {
        var vals = await asyncQuery(Sql, [projectId]);
        res.json(vals);
    } catch (error) {
        next(error)
    };
});

router.post('/url', async function (req, res, next) {
    var urlId = uuid();
    var data = {
        url_id: urlId,
        project_id: req.body.projectId,
        title: req.body.title,
        str: req.body.str,
        type: req.body.type,
        port: req.body.port,
        disable: 0,
    };

    var Sql = `INSERT INTO project_url SET ?`;
    try {
        await Permission.CPP(req.headers.token,  req.query.projectId);
        await asyncQuery(Sql, data);
        res.json({
            id: urlId
        });
    } catch (error) {
        next(error)
    };
})


router.put('/url', async function (req, res, next) {
    var urlId = req.body.urlId;
    var data = {
        title: req.body.title,
        str: req.body.str,
        type: req.body.type,
        port: req.body.port,
    };

    var Sql = `UPDATE project_url SET ? WHERE url_id = ?`;
    try {
        await Permission.CPP(req.headers.token,  req.query.projectId);
        await asyncQuery(Sql, [data, urlId]);
        res.json({});
    } catch (error) {
        next(error)
    };
});





router.delete('/url', async function (req, res, next) {
    var urlId = req.body.urlId;
    var Sql = `UPDATE project_url SET  disable = 1 WHERE url_id = ?`;
    try {
        await Permission.CPP(req.headers.token,  req.query.projectId);
        await asyncQuery(Sql, [urlId]);
        res.json({});
    } catch (error) {
        next(error)
    };
});




module.exports = router;